/*
 *  Copyright 2009 Piotr Soróbka <psorobka@gmail.com>.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

//package org.spicy.apples;


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import java.util.List;

/**
 *
 * @author Piotr Soróbka <psorobka@gmail.com>
 */
@Stateless
public class HelloBean implements HelloLocal {

	@PersistenceUnit 
	EntityManagerFactory entityManagerFactory;

    //@Override
    public String sayHello( String name ) {
		System.out.println( " ok " + entityManagerFactory );
		if ( null == entityManagerFactory ) {
			System.out.println( "entityManagerFactory is hosed" );
		} else {
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			System.out.println( " now " + entityManager );
			if ( null == entityManager ) {
				System.out.println( "entityManager is hosed" );
			} else {
System.out.println( "and.... " );
				entityManager.persist( new HelloEntity( name ) );
System.out.println( "yeah!!!!" );
			}
		}
        return "Hello, " + name;
    }

        /*
	public List getPagedData(SomeCriteriaObject someObject, int start, int page) {
		try {
			Criteria criteria = getSession().createCriteria(HelloEntity.class);
			//Build Criteria object here
			criteria.setFirstResult(start);
			criteria.setMaxResults(page);
			return criteria.list();
		} catch (HibernateException hibernateException) {
			//do something here with the exception
		}
	}    

	public int getDataCount(SomeCriteriaObject someObject) {
		Criteria criteria = getSession().createCriteria(HelloEntity.class);
		criteria.setProjection(Projections.rowCount());
		
		// Build Criteria object here
		Number nuofRecords = ((Number) criteria.uniqueResult());
		return nuofRecords == null ? 0 : nuofRecords.intValue();
	}

	public DataModel getMyPagedDataModel() {
		int totalListSize = getSomeBusinessService().getDataCount(getSomeCriteriaObject());
		List pagedList = getSomeBusinessService().getPagedData(getSomeCriteriaObject(), getTable1().getFirst(), getTable1().getRows());
		PagedDataModel dataModel = new PagedDataModel(pagedList, tatalListSize, getTable1().getRows());
		return dataModel;
	} 

        public List<HelloEntity> getItemsVLH(String pID, int start, int chunkSize) {
        	EntityManager em = entityManagerFactory.createEntityManager();      
        	Query query =
          		em.createQuery("SELECT i FROM greeted i WHERE i.ID_ = :pID");
        	query = query.setParameter("pID",pID);
        	query = query.setFirstResult(start);
        	query = query.setMaxResults(chunkSize);
        	List<HelloEntity>  items = query.getResultList();
        	em.close();
        	return items;
        } 
	*/ 

	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
 	public List<HelloEntity> getItems(int firstItem,int batchSize, String sortBy) {      
		EntityManager em = entityManagerFactory.createEntityManager();
        	//Query q = em.createQuery("select object(o) from greeted as o");
        	//Query q = em.createQuery("select x from HelloEntity x");
		Query q;
		if ( sortBy != null )
			q = em.createQuery("select x from HelloEntity x ORDER BY x." + sortBy);
		else
			q = em.createQuery("select x from HelloEntity x");

        	q.setMaxResults(batchSize);
        	q.setFirstResult(firstItem);
        	List<HelloEntity> items= q.getResultList();
        	return items;      
	}

        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
        public List<HelloEntity> getItemsByName(int firstItem,int batchSize) {
                EntityManager em = entityManagerFactory.createEntityManager();
                //Query q = em.createQuery("select x from HelloEntity x ORDER BY x.name ascending");
                Query q = em.createQuery("select x from HelloEntity x ORDER BY x.name_");
                q.setMaxResults(batchSize);
                q.setFirstResult(firstItem);
                List<HelloEntity> items= q.getResultList();
                return items;
        }

	public int getItemCount() {
		EntityManager em = entityManagerFactory.createEntityManager();
        	Query q = em.createQuery("select count(o) from HelloEntity as o");
        	int count = ((Long)q.getSingleResult()).intValue();
        	return count;
        }
}
